package com.hp.bon.sgw.util;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.hsqldb.Server;

/** * 启动HSQL服务器实例 **/
public class HSqlDBStarter {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(HSqlDBStarter.class);

	private Server server;
	private String dbPath;
	private String dbName;
	private int dbPort = 4900;
	private boolean startDB = true;

	public void start() {
		if (!startDB) {
			return;
		}
		logger.info("start SGW data store server at port " + dbPort + " dbpath:" + dbPath);
		try {
			server = new Server();
			server.setNoSystemExit(true);
			// 0表示第0个数据库，Server模式可以启动10个数据库
			server.setDatabasePath(0, dbPath + dbName);
			server.setDatabaseName(0, dbName);
			server.setPort(dbPort);
			server.setSilent(true);
			server.start();
		} catch (Exception e) {
			logger.warn("start sgw data store server failed,may be another instance started already:" + e);
		}
	}

	public void stop() {
		if (!startDB) {
			return;
		}
		logger.info("stop SGW data store server ");
		if (server != null) {
			server.stop();
		}

	}

	public void setDbPath(String dbPath) {
		this.dbPath = dbPath;
	}

	public void setDbName(String dbName) {
		this.dbName = dbName;
	}

	public void setDbPort(int dbPort) {
		this.dbPort = dbPort;
	}

	public static void main(String[] args) {
		Map<String, String> params = Comutils.parseArgs(args);
		String dbPath = params.get("dbpath");
		String dbName = params.get("dbname");
		String dbPort = params.get("dbport");
		HSqlDBStarter dbStarter = new HSqlDBStarter();
		dbStarter.setDbPath(dbPath);
		dbStarter.setDbName(dbName);
		dbStarter.setDbPort(Integer.parseInt(dbPort));
		dbStarter.start();
		try {
			Thread.currentThread().join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	public void setStartDB(boolean startDB) {
		this.startDB = startDB;
	}

}
